<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/03
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\goods;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Api\Controller\Tpmecms;


use ImiApp\ApiServer\Api\Model\Goodssku;
use ImiApp\ApiServer\Api\Model\GoodsskuPrice;

/**
 * 商品接口👔
 * @Auth(name="token",nologin={"no"})
 * @Controller("/goods.goods/")
 */
class Goods extends Tpmecms
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];



    /**
     * 添加收藏商品
     *
     * @param int $goods_id 商品id
     * @param int $goods_sku_price_id 价格id
     * @param int $num 数量默认1
     * @return void
     * @Action
     */
    public function add_likes(?int $goods_id, $goods_sku_price_id = null, ?int $num = 1)
    {
        if (!$num)
            $num = 1;
        $data['user_id'] = $this->auth->user()->id;
        if (!$goods_id) {
            return $this->error('没有商品');
        }
        $data['goods_id'] = $goods_id;
        $goods = $this->GetGoodsDataById($goods_id);
        $data['store_id']  = $goods['store_id'];
        if (!$goods['is_sku'])
            $goods_sku_price_id = Db::name('goodssku_price')->where('goods_id', '=', $goods_id)->value('id');
        $data['goods_sku_price_id'] = $goods_sku_price_id;

        $res = Db::name('likesgoods')->whereEx($data)->find();
        $data['num'] = $num;
        if ($res) {
            Db::name('likesgoods')->where('id', '=', $res['id'])->setFieldInc('num', $num)->update();
            Db::name('goods')->where('id', '=', $goods_id)->setFieldInc('likes', 1)->update();
        } else {
            $data['time'] = time();
            $data['id'] = Db::name('likesgoods')->insert($data)->getLastInsertId();
        }
        return $this->success('收藏成功');
    }



    /**
     * 编辑收藏商品
     *
     * @param int $id 收藏id
     * @param int $num 数量默认1
     * @param int $inc 加
     * @param int $dec 减
     * @return void
     * @Action
     */
    public function edit_likes(?int $id, ?int $num = 1,?int $inc = null,?int $dec = null)
    {
        if (!$num)
            $num = 1;
        $data['id'] = $id;
        $data['user_id'] = $this->auth->user()->id;
        // if (!$goods_id) {
        //     return $this->error('没有商品');
        // }
        // $data['goods_id'] = $goods_id;
        // $goods = $this->GetGoodsDataById($goods_id);
        // $data['store_id']  = $goods['store_id'];
        // if (!$goods['is_sku'])
        //     $goods_sku_price_id = Db::name('goodssku_price')->where('goods_id', '=', $goods_id)->value('id');
        // $data['goods_sku_price_id'] = $goods_sku_price_id;

        $res = Db::name('likesgoods')->whereEx($data)->find();
        // $data['num'] = $num;
        

        if ($inc) {
            Db::name('likesgoods')->where('id', '=', $res['id'])->setFieldInc('num', $num)->update();
            // Db::name('goods')->where('id', '=', $goods_id)->setFieldInc('likes', 1)->update();
        } else {
            if($res['num']<=$num){
                return $this->error('不能再减了',$res['num']);
            }
            Db::name('likesgoods')->where('id', '=', $res['id'])->setFieldDec('num', $num)->update();
        }
        $res = Db::name('likesgoods')->whereEx($data)->find();
        return $this->success('编辑成功',$res['num']);
    }


    /**
     * 删除收藏
     *
     * @param string|int $ids 收藏ids
     * @return void
     * @Action
     */
    public function del_likes($ids = null)
    {
        if(is_numeric($ids)){
            $where['id'] = $ids;
        }else{
            $where['id'] = ['in',explode(',',$ids)];          
        }
        $where['user_id'] = $this->auth->user()->id;
        $list = Db::name('likesgoods')->whereEx($where)->select()->getArray();
        if($list){
            foreach ($list as $key => $likesgoods) {
                $goods_id = $likesgoods['goods_id'];
                Db::name('goods')->where('id', '=', $goods_id)->setFieldDec('likes', 1)->update();
            }

            $res = Db::name('likesgoods')->whereEx($where)->delete();
        }

        if ($res)
            return $this->success('取消成功');
    }


    /**
     * 是否收藏商品
     *
     * @param int $goods_id 商品id
     * @param int $goods_sku_price_id 价格id
     * @return void
     * @Action
     */
    public function is_likes($goods_id, $goods_sku_price_id = null)
    {
        $where['goods_id'] = $goods_id;
        if ($goods_sku_price_id)
            $where['goods_sku_price_id'] = $goods_sku_price_id;
        $where['user_id'] = $this->auth->user()->id;
        $res = Db::name('likesgoods')->whereEx($where)->find();
        if ($res)
            return $this->success('已收藏', $res);
        return $this->success('未收藏', $res);
    }

    /**
     * 获取收藏列表
     *
     * @param integer|null $page 1
     * @param integer|null $limit 10
     * @return void
     * @Action
     */
    public function get_likes_list(?int $page = 1, ?int $limit = 10)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['user_id'] = $this->auth->user()->id;

        //循环店铺 最新在最上面
        $store_arr = Db::name('likesgoods')
            ->whereEx($where)
            ->orderRaw('time desc')
            ->fieldRaw('store_id')
            ->distinct(true)
            ->column('store_id');
        if ($store_arr) {
            $list_arr = Db::name('likesgoods')
                ->whereEx($where)
                ->orderRaw('time desc')
                ->fieldRaw('store_id,time,id')
                // ->distinct(true)
                ->whereIn('store_id', $store_arr)
                ->select()->getArray();
            $store_arr = [];
            foreach ($list_arr as $key => $val) {
                if (!in_array($val['store_id'], $store_arr))
                    $store_arr[] = $val['store_id'];
            }
        }
        //循环店铺 最新在最上面

        $list = [];
        if ($store_arr) {
            foreach ($store_arr as $key => $store_id) {

                $where['store_id'] = $store_id;
                $t_list = Db::name('likesgoods')
                    ->whereEx($where)
                    // ->whereIsNull('deletetime')
                    ->orderRaw('time desc')
                    ->page($page, $limit)
                    ->select()
                    ->getArray();
                if ($t_list) {
                    foreach ($t_list as $key => &$val) {
                        $val['goods'] = $this->getGoodsField($val);
                    }
                }
                $store = $this->getStoreData2($store_id);
                $list[] = ['store' => $store, 'list' => $t_list];
            }
        }


        return $this->success('', $list);
    }





    protected function getGoodsField($val)
    {
        $where['id'] = $val['goods_id'];
        $where['apply_status'] = '2';
        $goods = Db::name('goods')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->find();
        unset($goods['refuse_ps']);

        if ($val['goods_sku_price_id'])
            $goods['goods_sku_price'] = GoodsskuPrice::dbQuery()->where('id', '=', $val['goods_sku_price_id'])->find();
        // if ($goods['is_sku']) {
        //     $skuList = Goodssku::dbQuery()->whereEx(['pid' => 0, 'goods_id' => $goods['id']])->select()->getArray();
        //     if ($skuList) {
        //         foreach ($skuList as &$s) {
        //             $s['children'] = Goodssku::dbQuery()->whereEx(['pid' => $s['id'], 'goods_id' => $goods['id']])->select()->getArray();
        //         }
        //     }
        //     $goods['skuList'] = $skuList;

        //     $skuPrice = GoodsskuPrice::dbQuery()->whereEx(['goods_id' => $goods['id']])->select()->getArray();
        //     $goods['skuPrice'] = $skuPrice;
        // } else {
        //     // 将单规格的部分数据直接放到 goods 上
        //     $goodsSkuPrice = GoodsskuPrice::dbQuery()->where('goods_id','=', $goods['id'])->order('id', 'asc')->find();

        //     $goods['stock'] = $goodsSkuPrice['stock'] ?? 0;
        //     $goods['sn'] = $goodsSkuPrice['sn'] ?? "";
        //     $goods['weight'] = $goodsSkuPrice['weight'] ?? 0;
        //     $goods['stock_warning'] = $goodsSkuPrice['stock_warning'];

        //     $goods['skuList'] = [];
        //     $goods['skuPrice'] = [];
        // }

        return $goods;
    }



    // /**
    //  * 添加收藏商品
    //  *
    //  * @param int $id 商品id
    //  * @return void
    //  * @Action
    //  */
    // public function add_likes($id)
    // {
    //     $this->AddShoucang(3, $id, $this->auth->user()->id);
    //     return $this->success('收藏成功');
    // }


    // /**
    //  * 删除收藏商品
    //  *
    //  * @param int $id 商品id
    //  * @return void
    //  * @Action
    //  */
    // public function del_likes($id)
    // {
    //     $this->DelShoucang(3, $id, $this->auth->user()->id);
    //     return $this->success('取消收藏');
    // }


    // /**
    //  * 是否收藏商品
    //  *
    //  * @param int $id 商品id
    //  * @return void
    //  * @Action
    //  */
    // public function is_likes($id)
    // {

    //     return $this->success('goods', $this->IsShoucang(3, $id, $this->auth->user()->id));
    // }

}
